package king.dominic.jlibrary.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

import king.dominic.jlibrary.R;

import static android.view.View.MeasureSpec.makeMeasureSpec;

/**
 * Created by king on 2016/11/11.
 * MenuView
 */

public class MenuView extends ViewGroup {
    private Paint mPaint;
    private boolean drag;
    private boolean square;
    private int lineColor;
    private int space;
    private int column;
    private int row;
    private boolean isLongTouch = false;
    private float mLastTouchX;
    private float mLoasTouchY;

    public MenuView(Context context) {
        this(context, null);
    }

    public MenuView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MenuView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    @SuppressWarnings("unchecked")
    public <T> ArrayList<T> getChildren(){
        final  int count=getChildCount();
        ArrayList<T> list= new ArrayList<>();
        for(int i=0;i<count;i++){
            list.add((T)getChildAt(i));
        }
        return list;
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        mPaint = new Paint();
        mPaint.setColor(Color.TRANSPARENT);
        mPaint.setStrokeWidth(WindowUtil.dip2px(context, 1));
        if (attrs == null) return;

        TypedArray ta = getResources().obtainAttributes(attrs, R.styleable.MenuView);
        space = ta.getDimensionPixelSize(R.styleable.MenuView_mv_space, 0);
        column = ta.getInt(R.styleable.MenuView_mv_column, 4);
        lineColor = ta.getColor(R.styleable.MenuView_mv_line, Color.TRANSPARENT);
        square = ta.getBoolean(R.styleable.MenuView_mv_square, true);
        drag = ta.getBoolean(R.styleable.MenuView_mv_drag, false);
        row = ta.getInt(R.styleable.MenuView_mv_row, 2);
        ta.recycle();

        mPaint.setColor(lineColor);
        if (column == 0) column = 1;
        int count = getChildCount();
        int line = count / column + count % column == 0 ? 0 : 1;
        row = line > row ? line : row;
        row = row <= 0 ? 1 : row;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MenuView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        init(context, attrs, defStyleAttr);

    }

    private boolean isStartDrag = false;
    private Runnable checkLongTouch = new Runnable() {
        @Override
        public void run() {
            isStartDrag = isLongTouch;
        }
    };

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        int action = event.getAction() & MotionEvent.ACTION_MASK;
//        switch (action) {
//            case MotionEvent.ACTION_DOWN:
//                isLongTouch = true;
//                mLastTouchX=event.getX();
//                mLoasTouchY=event.getY();
//                postDelayed(checkLongTouch, 1000);
//                break;
//
//            case MotionEvent.ACTION_MOVE:
//                isLongTouch = false;
//                if (isStartDrag) {
//
//                }
//                break;
//            case MotionEvent.ACTION_UP:
//                isLongTouch = false;
//                isStartDrag = false;
//                break;
//            case MotionEvent.ACTION_CANCEL:
//                isLongTouch = false;
//                isStartDrag = false;
//                break;
//        }
//        return super.onTouchEvent(event);
//    }

    public int getColumn() {
        return column;
    }

    public void setColumn(int column) {
        if (column <= 0)
            throw new IllegalStateException("column can't less than or equal to zero!");
        if (column == this.column) return;
        this.column = column;
        requestLayout();
    }

    public int getRow() {
        return row;
    }

    public void setRow(int row) {
        if (row <= 0) throw new IllegalStateException("row can't less than or equal to zero!");
        if (row == this.row) return;
        this.row = row;
        requestLayout();
    }

    public int getSpace() {
        return space;
    }

    public void setSpace(int space) {
        if (space == this.space) return;
        this.space = space;
        requestLayout();
    }


    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (lineColor == Color.TRANSPARENT) return;
        final int count = getChildCount();
        final int line = count / column + (count % column == 0 ? 0 : 1);
        final int height = getHeight();
        final int width = getWidth();
        final int x = width / column;
        final int y = height / row;
        final int h = height / row * line;

        mPaint.setColor(Color.LTGRAY);
        canvas.drawRect(0, h, width, height, mPaint);

        mPaint.setColor(lineColor);
        for (int i = 1; i < column; i++) {
            canvas.drawLine(x * i, 0, x * i, h, mPaint);
        }
        for (int i = 0; i < row; i++) {
            canvas.drawLine(0, y * i, width, y * i, mPaint);
        }
    }

    private int mItemSize = 0;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);// 得到模式
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);// 得到尺寸
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        mItemSize = (widthSize - getPaddingStart() - getPaddingEnd() - (column - 1) * space) / column;

        if (square) {
            final int count = getChildCount();
            for (int i = 0; i < count; i++) {
                View child = getChildAt(i);
                LayoutParams lp = child.getLayoutParams();
                lp.width = lp.height = mItemSize;
            }
            final int mSpec = MeasureSpec.makeMeasureSpec(mItemSize, MeasureSpec.EXACTLY);
            measureChildren(mSpec, mSpec);
            final int line = count / column + (count % column == 0 ? 0 : 1);
            setMeasuredDimension(widthSize, mItemSize * line + (line - 1) * space+getPaddingTop()+getPaddingBottom());
            return;
        } else {
            measureChildren(makeMeasureSpec(mItemSize, widthMode), heightMeasureSpec);
        }
        int measureWidth = measureWidth(widthMode, widthSize);
        int measureHeight = measureHeight(heightMode, heightSize, (measureWidth - (column - 1) * space) / column);
        setMeasuredDimension(measureWidth, measureHeight);
    }

    @Override
    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 0, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 0, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

    private int measureWidth(int widthMode, int widthSize) {
        int result = 0;

        switch (widthMode) {
            case MeasureSpec.AT_MOST://不能超过最大尺寸
                View child = getChildAt(0);
                if (child == null) return 0;
                result = Math.min(widthSize, column * child.getMeasuredWidth() + space * (column - 1));
                break;
            case MeasureSpec.UNSPECIFIED://想要多大就多大
            case MeasureSpec.EXACTLY://设定了确定值
                result = widthSize;
                break;
        }
        return result;
    }

//    @Override
//    public void addView(View child, int index, LayoutParams params) {
//        if (square && mItemSize != 0) params.width = params.height = mItemSize;
//        super.addView(child, index, params);
//    }

    private int measureHeight(int heightMode, int heightSize, int widthSize) {
        int result = 0;


        switch (heightMode) {
            case MeasureSpec.UNSPECIFIED:
            case MeasureSpec.AT_MOST:
                int count = getChildCount();
                if (count == 0) return heightSize;
                int line = count / column + (count % column == 0 ? 0 : 1);
                line = line > row ? 0 : row - line;
                int height = 0;
                int max = 0;
                for (int index = 0; index < count; index++) {
                    max += index % column == 0 ? -max : 0;
                    View child = getChildAt(index);
                    int h = square ? widthSize : child.getMeasuredHeight();
                    max = Math.max(max, h == 0 ? child.getMeasuredWidth() : h);
                    height += index % column == column - 1 || index == count - 1 ? max : 0;
                }
                height += max * line + space * (line - 1);
                if (square) return height;
                result = MeasureSpec.UNSPECIFIED == heightMode ? height : (heightSize == 0 ? height : Math.min(height, heightSize));
                break;
            case MeasureSpec.EXACTLY:
                result = heightSize;
                break;
        }
        return result;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int pl = getPaddingStart();
        int pr = getPaddingEnd();
        int pt = getPaddingTop();
        int pb = getPaddingBottom();
        l += pl;
        t += pt;
        r -= pr;
        b -= pb;
        int count = getChildCount();
        int line = count / column + (count % column == 0 ? 0 : 1);
        if(!square) line = Math.max(line,row);
        final int width = (r - l - space * (column - 1)) / column;
        final int height = line == 0 ? 0 : (b - t - space * (line - 1)) / line;
        int left = 0;
        int top = 0;
        for (int index = 0; index < count; index++) {
            View child = getChildAt(index);

            int w;
            int h;

//            if (square) {
//                w = child.getMeasuredWidth();
//                h = child.getMeasuredHeight();
//            } else {
                w = width;
                h = height;
//            }

            //中心对称
            int wCorrect = (w - child.getMeasuredWidth()) / 2;
            int hCorrect = (h - child.getMeasuredHeight()) / 2;

            //padding
            left += index % column == 0 ? pl : space;
//            top += index < column ? pt : 0;
            top += index % column == 0 ? (index == 0 ? pt : space) : 0;

            child.layout(left + wCorrect, top + hCorrect, left + w - wCorrect, top + h - hCorrect);
            left += index % column == column - 1 ? -left : w;
            top += index % column == column - 1 ? h : 0;
        }
    }
}
